package com.baizhi.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {


    private static final String  SING = "!Q@W3e4r%T^YAOVr";
    
    /**生效时间的毫秒*/
    private static long iat;
    
    /**到期时间的毫秒*/
    private static long exp;
    
    /**
     * 生成token  header.payload.sing
     */
    public static String getToken(Map<String,String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);//默认7天过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        
        iat = System.currentTimeMillis();

        Date expireTime = instance.getTime();

        exp = expireTime.getTime();
        String token = builder.withExpiresAt(expireTime)//指定令牌过期时间
                .withIssuedAt(new Date(iat))
                .sign(Algorithm.HMAC256(SING));//sign


        return token;
    }

    public static Map<String,Long> getIatAndExp() {
        HashMap<String, Long> iatAndExp = new HashMap<>();
        iatAndExp.put("iat", iat);
        iatAndExp.put("exp", exp);
        return iatAndExp;
    }

    /**
     * 验证token 合法性
     *
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

//    /**
//     * 获取token信息方法
//     */
//    public static DecodedJWT getTokenInfo(String token){
//        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
//        return verify;
//    }

}
